<template>
	<view class="container">
		<view class="top">
			<swiper class="dswiper" circular :autoplay="true" :interval="5000" :current="current"
				@change="swiperchange">
				<swiper-item v-for="(item,index) in courseDetail.headerImageList" :key="index">
					<view class="swiper-item ">
						<img-item class="swiper-img" :src="item"></img-item>
					</view>
				</swiper-item>
			</swiper>
			<view v-if="courseDetail.headerImageList.length" class="swiper_num">
				{{current+1}}/{{courseDetail.headerImageList.length}}
			</view>
		</view>
		<view class="course_info" v-if="courseDetail">
			<view class="infol">
				<text class="one">预约费：<text class="integral">{{courseDetail.priceWithScore}}积分</text></text>
				<text class="two">课程费：<text class="price">￥{{courseDetail.priceWithCash}}</text>线下缴费</text>
			</view>
			<view class="infor">
				<text>报名人数: {{courseDetail.classInfo.currentNumber}}/{{courseDetail.classInfo.fullNumber}}</text>
				<text v-if="courseDetail.classInfo">剩余时间: {{compareTime(courseDetail.classInfo.registrationEndTime)}}</text>
				<text v-if="courseDetail.classInfo">截止: {{datechange(courseDetail.classInfo.registrationEndTime)}}</text>
			</view>
		</view>
		<view class="course_body" v-if="courseDetail">
			<view class="course_details">
				<view class="course_name">{{courseDetail.name}}</view>
				<view class="course_sign">
					<view class="sign_one">{{courseDetail.courseNodes}}节</view>
					<view  v-for="(label,idx) in courseDetail.labelList" :key="idx" class="sign_item">{{label}}</view>
				</view>
				<view class="details_introduction">
					<view class="spot">●</view>{{courseDetail.subtitle}}
				</view>
				<view class="course_services">服务机构：{{courseDetail.institutionName}}</view>
			</view>
			<view class="course_talent" v-if="talent">
				<view class="talent_top">
					<text>达人授课</text>
					<text class="gotalents" @click="goPage('/pages/talents/detail',{talentMobile:talent.talentMobile})">查看达人详情 ></text>
				</view>
				<view class="talent_itembody">
					<view class="item_img">
						<img-item :src="talent.introductionImageList[0]"></img-item>
					</view>
					<view class="item_info">
						<view class="item_title">{{talent.name}}</view>
						<item-score :score="talent.score"></item-score>
						<view class="item_sign">
							<view class="sign_item" v-for="(sv,sk) in talent.skillList" :key="sk">{{sv}}</view>
						</view>
						<view class="item_tip">本课程由社区达人提供授课，赶快参加吧！</view>
					</view>
				</view>
			</view>
			<view class="course_arrangement">
				<view class="arrangement_title">课程安排</view>
				<view class="arrangement_body">
					<view class="arow">
						<text class="frist">班级名称:</text>
						<text>{{courseDetail.classInfo.name}}</text>
					</view>
					<view class="arow">
						<text class="frist">开班时间:</text>
						<text v-if="courseDetail.classInfo">{{datechange(courseDetail.classInfo.openClassTime)}}</text>
					</view>
					<view class="arow" v-if="courseDetail.classInfo&&courseDetail.classInfo.classTimeList">
						<text class="frist">上课时间:</text>
						<text v-if="courseDetail.classInfo.classTimeList.length==1">
							每{{intToWord(courseDetail.classInfo.classTimeList[0].week)}} {{courseDetail.classInfo.classTimeList[0].startTime.slice(0,-3)}}~{{courseDetail.classInfo.classTimeList[0].endTime.slice(0,-3)}}
						</text>
						<view v-else class="classtime">
							<text v-for="(classtime,idx) in courseDetail.classInfo.classTimeList" :key="idx">
								每{{intToWord(classtime.week)}} {{classtime.startTime.slice(0,-3)}}~{{classtime.endTime.slice(0,-3)}}
							</text>
						</view>
					</view>
				</view>
			</view>
			<view class="course_steps">

			</view>
			<view class="course_introduction">
				<view class="introduction_body">
					<view class="introduction_title">课程简介</view>
					<view class="introduction_info" :class="{open:moreshowFlag&&moreState}">
						<rich-text class="introduction_text" :nodes="introduction"></rich-text>
					</view>
				</view>
				<view class="more" v-if="moreshowFlag" @click="moreState=!moreState">{{moreState?"更多":"收起"}}简介
					<uni-icons v-show="moreState" type="bottom" color="#7F7F7F"></uni-icons>
					<uni-icons v-show="!moreState" type="top" color="#7F7F7F"></uni-icons>
				</view>
			</view>
			<view class="course_img">
				<image class="img2" v-for="(inimg,idx) in imageList2" :key="idx" :src="inimg"
				:id="'img'+idx" @load="getImgInfo" :style="{height: imageListHeight[idx] + 'px'}">
				</image>
				<view class="more" v-show="imageList.length > 1" @click="showMoreImg">
					{{moreState2?"更多":"收起"}}
					<uni-icons v-show="moreState2" type="bottom" color="#7F7F7F"></uni-icons>
					<uni-icons v-show="!moreState2" type="top" color="#7F7F7F"></uni-icons>
				</view>
			</view>
		</view>
		<view class="course_foot">
			<button class="button foot_share" open-type="share"><text class="foot_text">分享</text></button>
			<button class="foot_appointment" type="default" @click="popup()" :disabled="appointmentflag">{{text}}</button>
		</view>
		<uni-popup ref="appointment"  type="bottom">
		    <view class="popup">
		    	<view class="popup_top">
		    		<view class="appointment_img">
		    			<img-item class="swiper-img" :src="courseDetail.cover"></img-item>
		    		</view>
		    		<view class="appointment_info">
		    			<view class="appointment_title">{{courseDetail.name}}</view>
		    			<view class="appointment_jf">{{courseDetail.priceWithScore}}积分</view>
		    			<view class="appointment_kc">
		    				<view class="sign_one">1节</view>
		    			</view>
		    		</view>
		    	</view>
		    	<view class="enrollment">
		    		<view class="one">报名方式：</view>
		    		<view class="two">
		    			<view class="twol">积分预约</view>
		    			<view class="twor">{{courseDetail.priceWithScore}}积分</view>
		    		</view>
		    		<view class="there">积分余额：{{ userScore }}</view>
		    	</view>
				<view class="information">
					<view class="information_row information_name">
						<text>学员姓名</text>
						<input class="information_input" type="text" placeholder="该用户的社区姓名" @input="userName" maxlength="10"/>
					</view>
					<view class="information_row information_contact">
						<text>联系方式</text>
						<input class="information_input" type="number" v-model="user_phone" placeholder="该用户的社区手机号"  @input="userPhone"  @blur="phoneblur(user_phone)" maxlength="11"/>
					</view>
					
				</view>
				<view class="tips">
					报名成功后积分不可退换,不可取消.课程费请到社区联系机构自行缴费.
				</view>
				<button class="appointment" type="default" @click="appointment()" :disabled="appointmentflag2">{{popuptext}}</button>
				<view class="agreement">
					点击“立即报名”表示已阅读并同意<text class="agreements">《社区上课协议》</text>和<text class="agreements">《用户协议》</text>
				</view>
		    </view>
		</uni-popup>
		<uni-popup ref="success"  type="center">
			<view class="success">
				<view class="one">预约成功</view>
				<view class="two">请在规定时间内前往线下机构完成缴费，过时订单将会取消</view>
				<button class="vieworder" type="default" @click="vieworder()">查看订单</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import * as api from "@/http/api";
	import itemScore from "@/components/base/item-score.vue";
	export default {
		components:{itemScore},
		data() {
			return {
				current: 0,
				text:"立即预约",
				popuptext: "立即预约",
				user_phone:'',
				phoneFlag:false,
				user_name:'',
				appointmentflag:true,
				appointmentflag2:false,
				classid:"",
				courseDetail:null,
				talent:null,
				introduction:"",
				orderid:"",
				imageList:[],
				imageList2:[],
				imageListHeight:[],
				moreshowFlag: false,
				moreState:1,
				moreState2:true,
				type: '',
			}
		},
		onLoad(event) {
			const content = event.content;
			let detailObj = {};
			try {
				detailObj = JSON.parse(decodeURIComponent(content));
			} catch (error) {
				detailObj = JSON.parse(content);
			}
			this.type = detailObj.type
			this.classid = detailObj.id
			this.getCourseDetail();
			this.getScore();
		},
		// #ifdef MP-WEIXIN
		onShareAppMessage() {
			const param = encodeURIComponent(JSON.stringify({id: this.classid}))
			return {
				title: '学堂课程详情',
				path: `/pages/school/detail/index?content=${param}&isRedirectUrl`
			}
		},
		// #endif
		methods: {
			getCourseDetail(){
				let data = {}
				let url = ''
				this.type ? data.registrationId = this.classid : data.id = this.classid
				this.type ? url = api.getMycourseDetail : url = api.coursedetail
				console.log(api.coursedetail)
				this.$request({
					url: url,
					data: data
				}).then(res=>{
					if(!res){
						return false;
					}
					this.appointmentflag = false;
					this.courseDetail=res;
					this.introduction=res.introduction;
					this.$nextTick(()=>{
						this.getIntroduction();
					})
					this.imageList=res.introductionImageList;
					this.imgList();
					res.introductionImageList.forEach((item) => {
					    this.imageListHeight.push(0);
					});
					if(res.classInfo){
						if(res.classInfo.currentNumber >= res.classInfo.fullNumber){
							this.text="名额已满";
							this.appointmentflag = true;
						}
						const _time = new Date().getTime();
						const startTime = new Date(res.classInfo.registrationStartTime).getTime();
						const endTime = new Date(res.classInfo.registrationEndTime).getTime();
						if(_time < startTime){
							this.text="报名未开始";
							this.appointmentflag = true;
						}
						if(_time >= endTime){
							this.text="报名已截止";
							this.appointmentflag = true;
						}
					}
					if(res.talent)this.talent = res.talent;
					if(res.isRegistered){
						this.text = "已预约";
						this.appointmentflag = true;
					}
				})
			},
			appointment(){
				let name = this.user_name;
				let phone = this.user_phone;
				if(name && phone && this.classid){
					this.phoneblur(phone);
					if(!this.phoneFlag)return;
					this.$request({
						url: api.courseregister,
						data: {	
							id:this.classid,
							mobile:phone,
							name:name,
						},
						method: 'POST'
					}).then(res=>{
						this.orderid=res;
						this.$refs.appointment.close();
						this.text = "已预约";
						this.popuptext = "已预约";
						this.appointmentflag = true;
						this.appointmentflag2 = true;
						this.$refs.success.open();
					})
				}else{
					if(name==null || name==""){
						uni.showToast({
							title:'请输入学员姓名',
							icon:'none'
						})
						return false;
					}
					if(phone==null || phone==""){
						uni.showToast({
							title:'请输入联系方式',
							icon:'none'
						})
						return false;
					}
				}
			},
			getIntroduction(){
				const query = uni.createSelectorQuery().in(this);
				query.select('.introduction_info').boundingClientRect(data => {
					if(data.height>100){
						this.moreshowFlag = true;
					}
				}).exec();
			},
	     	getImgInfo (e) {
				var _this = this;
				var id = e.currentTarget.id;
				var index = id.substr(3);
				var item = _this.imageListHeight [index];
				const query = uni.createSelectorQuery().in(this);
				query.select('#' + id).boundingClientRect(data => {
					_this.imageListHeight [index] = data.width * e.detail.height / e.detail.width;
					_this.$forceUpdate();
				}).exec();
	        },
			showMoreImg(){
				this.moreState2 = !this.moreState2;
				this.imgList();
			},
			imgList(){
				//如果moreState为ture
				//如果图片列表大于1条，取第一条，小于等于一条，取所有
				if (this.moreState2) {
					if (this.imageList&&this.imageList.length > 1) {
						this.imageList2 = this.imageList.slice(0,1);
					} else {
						this.imageList2 = this.imageList;
					}
				}
				//如果moreState为false，展示所有
				if (!this.moreState2) {
					this.imageList2 = this.imageList;
				}
			},
			compareTime(deadline){
				let oDate1 = new Date(deadline);
				//let oDate1 = new Date("2022-04-13");
				let oDate2 = new Date();
				let days=0;
				let comparet=oDate1.getTime()-oDate2.getTime();
				if(comparet>0){//报名中
					let comparet=oDate1.getTime()-oDate2.getTime();
					let tempdays=Math.floor(comparet/(24 * 3600 * 1000));
					if(tempdays>0){
						days=tempdays+" 天";
					}else{
						let temphours=Math.floor(comparet/(3600 * 1000));
						if(temphours>0){
							days=temphours+" 小时";
						}else{
							if(Math.floor(comparet/(60 * 1000))==0){
								days=Math.floor(comparet/1000)+" 秒";
							}else{
								days=Math.floor(comparet/(60 * 1000))+" 分钟";
							}
						}
					}
				}else{ 
					 days= 0+" 天";
				}
				return days;
			},
			datechange(time){
				return time.split(" ")[0].replaceAll("-",".")
			},
			intToWord(week){
				let day;
				switch (week) {
				  case 7:
				    day = "周日";
				    break;
				  case 1:
				    day = "周一";
				    break;
				  case 2:
				    day = "周二";
				    break;
				  case 3:
				    day = "周三";
				    break;
				  case 4:
				    day = "周四";
				    break;
				  case 5:
				    day = "周五";
				    break;
				  case  6:
				    day = "周六";
				}
				return day;
			},
			swiperchange(e){
				this.current = e.detail.current;
			},
			popup(){
				if(this.appointmentflag) return
				this.toAutorize()
				if(this.$store.state.authStatus === 'UNAUTHORIZED') return
				if(this.userScore<this.courseDetail.priceWithScore){
					this.popuptext = "积分不足";
					this.appointmentflag2 = true;
				}
				this.$refs.appointment.open();
			},
			vieworder(){
				uni.navigateTo({
					url: '/pages/user/order/detail?id=' + encodeURIComponent(JSON.stringify(this.orderid))
				});
			},
			userName(event){
				this.user_name = event.target.value;
			},
			userPhone(e){
				let val = e.target.value.replace(/(^\s*)|(\s*$)/g, "");
				if (!val) {
					this.user_phone = '';
					return
				}
				var reg = /[^\d]/g
				val = val.replace(reg, "");
				this.$nextTick(() => {
					this.user_phone = val;
				})
			},
			phoneblur(reg_tel){//验证手机号
				console.log("验证手机号",reg_tel)
				if (reg_tel !== '') {
				    var reg=/^1[3456789]\d{9}$/;
				    if(!reg.test(reg_tel)){
						uni.showToast({
							title: '请输入有效的手机号码',
							duration: 1500,
							icon:"none"
						})
						this.phoneFlag = false;
					}else{
						this.phoneFlag = true;
					}
				}			
			},
		}
	}
</script>

<style lang="scss">
	@import "./index.scss";
</style>
